package com.atguigu.myjuc.demo;

import java.util.concurrent.*;

/**
 * 线程池
 */
public class MyThreadPoolDemo {
    public static void main(String[] args) {
        /*
        * 线程池大小的设置
        * CPU密集型 N(CPU)数+1
        * IO密集型 N(CUP)数*2
        * */
        System.out.println(Runtime.getRuntime().availableProcessors());

        ExecutorService threadPool = new ThreadPoolExecutor(
                2,
                5,
                1L,TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy());

        try {
            for (int i = 1; i <= 16; i++) {
                int finalI = i;
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+" \t"+"给顾客:"+ finalI +" \t办理业务");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }
    }

    public static void initPool(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
//        ExecutorService threadPool = Executors.newSingleThreadExecutor();
//        ExecutorService threadPool = Executors.newCachedThreadPool();
        try {
            for (int i = 1; i <= 20; i++) {
                int finalI = i;
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+" \t"+"给顾客:"+ finalI +" \t办理业务");
                    //暂停亳秒
                    try { TimeUnit.MICROSECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }
    }
}
